package com.cq.school.web;

import com.cq.school.entity.Pictures;
import com.cq.school.service.SchoolService;
import org.apache.poi.ss.examples.html.ToHtml;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: huke
 * Date: 13-12-5
 * Time: 下午10:47
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class UploadAction {

    @Autowired
    private SchoolService schoolService;
    private String baseImgUrl = "/upload";
    private long maxSize = 2097152;
    private static HashMap<String, String> extMap;
    private static SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    static {
        extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
    }
    @RequestMapping(value = "/uploadExcel.do")
    @ResponseBody
    public  Object uploadExcel(HttpServletRequest request) {
        Map map = new HashMap();
        MultipartFile file = ((MultipartHttpServletRequest)request).getFile("file");
        if(file!=null&&!file.isEmpty())
        {
            InputStream in = null;
            StringWriter out = null;
            try {
               in  = file.getInputStream();
                out = new StringWriter();
                ToHtml.create(in,out).print();
                map.put("table",out.toString());

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(in!=null)
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                if(out!=null)
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        }
        map.put("result","ok");
        return map;
    }

    @RequestMapping(value = "/uploadImage.do")
    @ResponseBody
    public Object uploadImg(HttpServletRequest request){
        MultipartFile file = ((MultipartHttpServletRequest)request).getFile("imgFile");
        if(file!=null&&!file.isEmpty())
        {
            String time = df.format(new Date());
            String  saveUrl = baseImgUrl+"/"+time.substring(0,6);
            String savePath  = request.getSession().getServletContext().getRealPath(baseImgUrl);
            savePath += "/"+time.substring(0,6);
            //检查文件大小
            if(file.getSize() > maxSize){
                return getResult(false, "上传文件大小超过限制。");
            }
            //检查扩展名
            String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
            if(!Arrays.<String>asList(extMap.get("image").split(",")).contains(fileExt)){
                return getResult(false, "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get("image") + "格式。");
            }
            String newFileName = time + "_" + new Random().nextInt(1000) + "." + fileExt;
            File targetFile = new File(savePath+"/"+newFileName);
            if(!targetFile.getParentFile().exists())
                targetFile.mkdirs();
            try {
                file.transferTo(targetFile);
                return getResult(true,saveUrl+"/"+newFileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    private Map getResult(boolean success,String msg){
        return getResult(success, msg,0);
    }
    private Map getResult(boolean success,String msg,long id){
        Map map = new HashMap();
        map.put("error",success?0:1);
        map.put(success?"url":"message",msg);
        if(id>0)
            map.put("id",id);
        return map;
    }

    @RequestMapping(value = "/uploadSchoolPic.do")
    @ResponseBody
    public Object uploadSchoolPic(HttpServletRequest request){
        long schoolId = Long.parseLong(request.getParameter("schoolId"));
        MultipartFile file = ((MultipartHttpServletRequest)request).getFile("file");
        if(file!=null&&!file.isEmpty())
        {
            String time = df.format(new Date());
            String  saveUrl = baseImgUrl+"/"+time.substring(0,6);
            String savePath  = request.getSession().getServletContext().getRealPath(baseImgUrl);
            savePath += "/"+time.substring(0,6);
            //检查文件大小
            if(file.getSize() > maxSize){
                return getResult(false, "上传文件大小超过限制。");
            }
            //检查扩展名
            String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
            if(!Arrays.<String>asList(extMap.get("image").split(",")).contains(fileExt)){
                return getResult(false, "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get("image") + "格式。");
            }
            String newFileName = time + "_" + new Random().nextInt(1000) + "." + fileExt;
            File targetFile = new File(savePath+"/"+newFileName);
            if(!targetFile.getParentFile().exists())
                targetFile.mkdirs();
            try {
                file.transferTo(targetFile);
                Pictures pictures = new Pictures();
                pictures.setSchoolId(schoolId);
                pictures.setUrl(saveUrl+"/"+newFileName);
                schoolService.saveSchoolPicture(pictures);
                return getResult(true,saveUrl+"/"+newFileName,pictures.getId());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
